import pygame
from typing import Tuple

from game.stat import Stat
from game.sprites.base import Entity, Frames
from game.sprites.player.inventory import Inventory
from game.world.coordinate import Coordinate
from game.data.plot.plot import Dialog
from game.container import Variables, CONSTANT,Direction
from game.ui.menus import Menus


class Player(Entity):
   
    def __init__(
        self,
        
        coordinate: Coordinate,
        
        groups: Tuple[pygame.sprite.Group, ...],
        frames: Frames,
        
        stat: Stat | None = None,
        dialog: Dialog | None = None,
        can_interact: bool = False,
        can_communicate: bool = False
    ):
        super().__init__(coordinate, groups, frames, dialog, can_interact, can_communicate)
        
        self.stat = stat or Stat()
        self.inventory = Inventory
        self.hp = self.stat.health
        self.mana = self.stat.intelligence
        self.hitInterval = -1

    
    def moveTo(self, dest: Coordinate) -> bool:
        # raise NotImplementedError
        pass

    def collision(self):
        from game.sprites.sprites import GroupsContainer
        for sprite in GroupsContainer.obstacle_group.sprites():
            offset_x = sprite.rect.left - self.rect.left
            offset_y = sprite.rect.top - self.rect.top
            if self.mask.overlap_area(sprite.mask, (offset_x, offset_y)):
                dx = self.mask.overlap_area(sprite.mask, ( offset_x+1, offset_y)) - self.mask.overlap_area(sprite.mask, ( offset_x- 1, offset_y))
                dy = self.mask.overlap_area(sprite.mask, (offset_x,  offset_y+1)) - self.mask.overlap_area(sprite.mask, (offset_x, offset_y- 1))
                self.rect.move_ip(dx/30, dy/30)
    def interactWithEntity(self, entity: Entity):
        if entity.can_communicate:
            Menus.game_menu.component_list[0].start_dialog(entity)

    def interactWithNearestEntity(self) -> None:
        entity = Variables.world.getEntityAroundPlayer(CONSTANT.PLAYER.MAX_INTERACT_RADIUS, sort="nearest") # type: ignore
        for i in range(len(entity)):
            if entity[i].can_interact and (not entity[i].is_barrier):
                self.interactWithEntity(entity[i])
                return
                    
    def update(self) -> None:
        self.collision()
        super().update()

        # print('current_topleft', self.current_topleft, 'last_topleft', self.last_topleft)

        
        if self.direction != self.frames.direction:
            self.frames.change_direction(self.direction)
        if self.direction != Direction.NONE:
            
            vec = pygame.math.Vector2(self.direction.value).normalize() * self.speed * 1.5
            
            pred = self.coordinate + vec
            
            if (50 < pred.x < 3200 - 50) and (50 < pred.y < 3648 - 50):            
                self.rect.move_ip(vec)
                self.coordinate = pred